package bacnetnetwork1;

import com.serotonin.bacnet4j.LocalDevice;
import com.serotonin.bacnet4j.exception.BACnetException;
import com.serotonin.bacnet4j.exception.BACnetServiceException;
import com.serotonin.bacnet4j.npdu.ip.IpNetwork;
import com.serotonin.bacnet4j.obj.BACnetObject;
import com.serotonin.bacnet4j.type.Encodable;
import com.serotonin.bacnet4j.type.enumerated.EngineeringUnits;
import com.serotonin.bacnet4j.type.enumerated.ObjectType;
import com.serotonin.bacnet4j.type.enumerated.PropertyIdentifier;
import com.serotonin.bacnet4j.type.primitive.CharacterString;
import com.serotonin.bacnet4j.type.primitive.Real;

public class CreateSensor {
    public LocalDevice createSensor(int ID, String networkAddress, String deviceAddress, int port, String name, EngineeringUnits units) throws Exception {
        
        // Create Sensor as LocalDevice
        LocalDevice sensor = new LocalDevice(ID, networkAddress,deviceAddress);        
        sensor.getConfiguration().setProperty(PropertyIdentifier.objectName,
                new CharacterString(name));
        sensor.setPort(port);
        // localDevice.getConfiguration().setProperty(PropertyIdentifier.segmentationSupported,
        // Segmentation.noSegmentation);
        
        BACnetObject ai1 = new BACnetObject(sensor,
                sensor.getNextInstanceObjectIdentifier(ObjectType.analogInput));
        ai1.setProperty(PropertyIdentifier.objectName, new CharacterString("Sensor "+ ID + " output"));
        ai1.setProperty(PropertyIdentifier.units, units);
        sensor.addObject(ai1);

        BACnetObject av1 = new BACnetObject(sensor,
                sensor.getNextInstanceObjectIdentifier(ObjectType.analogValue));
        av1.setProperty(PropertyIdentifier.objectName, new CharacterString("Value of Sensor "+ID+ " output"));
        av1.setProperty(PropertyIdentifier.relinquishDefault, new Real(0.0000F));
        sensor.addObject(av1);
        
        // Start Sensor 1.
        sensor.initialize();
        return sensor;
        
    }
    
    public boolean setSensorValue(LocalDevice sensor, String ID, float givenValue) throws BACnetServiceException {
        float aivalue=givenValue;
        BACnetObject av=sensor.getObject("Value of Sensor "+ID+" output"); 
        av.setProperty(PropertyIdentifier.presentValue, new Real(aivalue));        
        return false;
    }
        
    public Encodable getSensorValue(LocalDevice sensor,String ID) throws BACnetServiceException {        
        BACnetObject av=sensor.getObject("Value of Sensor "+ID+" output"); 
        Encodable currentValue=av.getProperty(PropertyIdentifier.presentValue);
        return currentValue;        
    }
}
